package com.heima.schedule.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.common.cache.CacheService;
import com.heima.common.constants.ScheduleConstants;
import com.heima.model.schedule.dto.Task;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.service.TaskService;
import com.heima.schedule.service.TaskinfoLogsService;
import com.heima.schedule.service.TaskinfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * @author tongdulong@itcast.cn
 * @since 2022-07-13
 */
@Service
@Slf4j
public class TaskServiceImpl implements TaskService {

    @Autowired
    private TaskinfoService taskinfoService;

    @Autowired
    private TaskinfoLogsService taskinfoLogsService;

    @Autowired
    private CacheService cacheService;

    //    初始化数据
    @Scheduled(fixedRate = 1000 * 5 * 60)
    @PostConstruct   //这个注解就是在启动容器的时候，预加载的资源
    public void reloadData(){
        //清除队列
        clear();
        //查询taskinfo
        List<Taskinfo> taskinfoList = taskinfoService.list();
        if (CollectionUtils.isEmpty(taskinfoList)){
            log.warn("任务为空");
            return;
        }
        for (Taskinfo taskinfo : taskinfoList) {
            if (taskinfo == null){
                continue;
            }
            long executeTime = taskinfo.getExecuteTime().getTime();
            long currentTime = System.currentTimeMillis();
            long futureTime = currentTime + (1000 * 60 * 5);

            Task task = new Task();
            BeanUtils.copyProperties(taskinfo,task);
            task.setExecuteTime(executeTime);

            if (executeTime <= currentTime){
                //小于当前时间  放入执行队列
                cacheService.lLeftPush(ScheduleConstants.TOPIC,JSON.toJSONString(task));
            }else if(executeTime <= futureTime){
                //else 小于未来五分钟，放到未来队列
                cacheService.zAdd(ScheduleConstants.FUTURE,JSON.toJSONString(task),executeTime);
            }
        }
    }

    //清除队列
    public void clear(){
        cacheService.delete(ScheduleConstants.FUTURE);
        cacheService.delete(ScheduleConstants.TOPIC);
    }

    /**
     * 定时任务
     */
    //todo
    @Override
    @Scheduled(fixedRate = 1000 * 60)
    public void refresh() {
        log.info("定时任务执行===");

        String token = cacheService.tryLock("FUTURE_TASK_SYNC", 1000 * 30);
        if (StringUtils.isBlank(token)){
            return;
        }
        //向这个未来队列发送指令，然后通过管道将任务数组发送到执行队列
        //从未来队列拿到已过期的任务
        Set<String> tasks = cacheService.zRangeByScore(ScheduleConstants.FUTURE, 0, System.currentTimeMillis());
        if (!tasks.isEmpty()){
            cacheService.refreshWithPipeline(ScheduleConstants.FUTURE,ScheduleConstants.TOPIC,tasks);
            System.out.println("成功将未来队列中的任务，通过管道转移到执行队列");
        }
        //将任务从未来队列通过管道放到执行对嘞
    }

    /**
     * 消费任务
     * @return
     */
    @Override
    public Task poll() {
        // 消费任务，弹出队列中的任务
        String taskString = cacheService.lRightPop(ScheduleConstants.TOPIC);
        if (StringUtils.isEmpty(taskString)){
            log.warn("弹出任务为空");
            return null;
        }
        Task task = JSON.parseObject(taskString, Task.class);
        //删除taskinfo
        Long taskId = task.getTaskId();
        boolean taskinfoResult = taskinfoService.removeById(taskId);
        if (!taskinfoResult){
            log.warn("任务列表删除失败");
            return null;
        }
        //修改taskinfolog状态
        TaskinfoLogs taskinfoLogs = taskinfoLogsService.getById(taskId);
        if (taskinfoLogs == null){
            log.warn("taskinfolog为空");
            return null;
        }
        taskinfoLogs.setStatus(ScheduleConstants.EXECUTED);
        boolean logResult = taskinfoLogsService.updateById(taskinfoLogs);
        if (!logResult){
            log.warn("日志更新失败");
            return null;
        }
        return task;
    }

    /**
     * 取消任务
     * @param taskId
     * @return
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public Boolean cancelTask(Long taskId) {
        //删除taskInfo表中的数据
        boolean taskinfoResult = taskinfoService.removeById(taskId);
        if (!taskinfoResult){
            log.warn("删除taskinfo数据失败");
            return false;
        }
        //修改taskinfolog表的中的状态为已取消
        TaskinfoLogs taskinfoLogs = taskinfoLogsService.getById(taskId);
        taskinfoLogs.setStatus(2);
        boolean logResult = taskinfoLogsService.updateById(taskinfoLogs);
        if (!logResult){
            log.warn("日志更新失败");
            throw new RuntimeException("日志更新失败");
        }
        //根据id查询出Task,然后删除两个队列中务对应的任
        Task task = new Task();
        BeanUtils.copyProperties(taskinfoLogs,task);
        task.setExecuteTime(taskinfoLogs.getExecuteTime().getTime());

        if (task.getExecuteTime() <= System.currentTimeMillis()){
            //代表该任务已经过期，在执行队列中
            cacheService.lRemove(ScheduleConstants.TOPIC,0,JSON.toJSONString(task));
        }else{
            //代表任务还没执行，在待执行队列中
            cacheService.zRemove(ScheduleConstants.FUTURE,JSON.toJSONString(task));
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public long addTask(Task task) {
        // 添加任务到task
        long executeTime = task.getExecuteTime();
        Taskinfo taskInfo = new Taskinfo();
        BeanUtils.copyProperties(task, taskInfo);
        taskInfo.setExecuteTime(new Date(executeTime));
        boolean taskResult = taskinfoService.save(taskInfo);
        if (!taskResult) {
            log.warn("任务添加失败");
            throw new RuntimeException("任务添加失败");
        }
        // 添加任务到log
        TaskinfoLogs taskinfoLogs = new TaskinfoLogs();
        BeanUtils.copyProperties(taskInfo, taskinfoLogs);
        taskinfoLogs.setExecuteTime(new Date(executeTime));
        taskinfoLogs.setStatus(ScheduleConstants.SCHEDULED);
//        taskinfoLogs.setVersion(1);
        boolean logResult = taskinfoLogsService.save(taskinfoLogs);
        if (!logResult) {
            log.warn("任务日志添加失败");
            throw new RuntimeException("任务日志添加失败");
        }
        task.setTaskId(taskInfo.getTaskId());
        addTaskToCache(task);
        // 返回任务id
        return taskInfo.getTaskId();
    }

    public void addTaskToCache(Task task) {
        long executeTime = task.getExecuteTime();
        long currentTimeMillis = System.currentTimeMillis();
        long futureTime = currentTimeMillis + (5 * 60 * 1000);
        // 如果小于当前就写入list
        String listKey = ScheduleConstants.TOPIC;
        // 如果小于五分钟后，就写入zset
        String zSetKey = ScheduleConstants.FUTURE;
        if (executeTime <= currentTimeMillis) {
            cacheService.lLeftPush(listKey, JSON.toJSONString(task));
        } else if (executeTime <= futureTime) {
            cacheService.zAdd(zSetKey, JSON.toJSONString(task), executeTime);
        }
    }

}